package com.abocode.aichat.app.web;

import com.abocode.aichat.app.api.command.LoginCommand;
import com.abocode.aichat.app.user.api.command.CreateUserCommand;
import com.abocode.aichat.app.user.model.User;
import com.abocode.aichat.app.user.model.UserIdentity;
import com.abocode.aichat.app.user.service.UserService;
import com.abocode.aichat.app.user.vo.UserVo;
import com.abocode.aichat.app.utils.ConfigUtils;
import com.abocode.aichat.app.utils.EncryptionUtils;
import com.abocode.aichat.app.utils.StringUtil;
import com.abocode.aichat.app.vo.AuthorizationVo;
import com.abocode.aichat.app.vo.HttpHelper;
import com.abocode.aichat.app.vo.ResponseBuilder;
import com.iflytek.application.common.springjdbc.Pagination;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.text.SimpleDateFormat;
import java.util.*;

/***
 *   Created by guanxf on 2015/12/16.
 */
@RestController
@RequestMapping("/unlogins")
@Slf4j
public class UnLoginController {
    @Autowired
    private UserService jdbcUserService;
    @Autowired
    private UserService userService;
    @Autowired
    private  HttpHelper httpHelper;

    @Value("${auth.token.version}")
    private int tokenVersion;
    @RequestMapping(value = "/gettime",method = RequestMethod.GET)
    public Object  getTime() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Map map=new HashMap();
        map.put("time",sdf.format(new Date()));
        return ResponseBuilder.success(map);
    }

    @RequestMapping(value = "/user/create", method = RequestMethod.POST)
    public Object create(@RequestBody @Valid CreateUserCommand createUserCommand, HttpServletRequest request) {
        AuthorizationVo authorizationVo= httpHelper.getAuthorizationVo(request);
        User user;
        if(StringUtil.isNullOrEmpty(createUserCommand.getIdentity())){
            user=userService.create(createUserCommand,  authorizationVo);
        }else{
            UserIdentity userIdentity=	userService.findByIdentity(createUserCommand.getIdentity());
            if(StringUtil.isNullOrEmpty(userIdentity)){
                user=userService.create(createUserCommand,  authorizationVo);
            }else{
                user=  userService.findOne(userIdentity.getUid());
            }
        }
        String token=this.getToken(user,request);
//        jedis.setex(Constant.SNSREDIS.SNSUSR, 30*24*60*60, token);
        Map map=new HashMap();
        map.put("token",token);
        map.put("id",user.getId());
        return ResponseBuilder.success(map);
    }

    @RequestMapping(value = "/user/find-luck", method = RequestMethod.GET)
    public Object find (Pageable pageable) {
        Pagination users=  jdbcUserService.findAllWithRandom(pageable);
        if(null!=users.getContent()){
            List<UserVo> userList= (List<UserVo>) users.getContent();
            String url= ConfigUtils.get("resource.public.url");
            for (UserVo user:userList){
                String avatar=user.getAvatar();
                if(!StringUtil.isNullOrEmpty(avatar)){
                    user.setAvatar(url+avatar);
                }
            }
            users.setContent(userList);
        }
        return ResponseBuilder.success(users);
    }



    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    public Object login(@RequestBody @Valid LoginCommand loginCommand, HttpServletRequest request)   throws Exception{
        User  user=    userService.login(loginCommand.getLoginname(), loginCommand.getPassword());
       String token=this.getToken(user,request);
//       jedis.setex(Constant.SNSREDIS.SNSUSR, 30*24*60*60, token);
        Map  map=new HashMap();
        map.put("token",token);
        map.put("id",user.getId());
        return ResponseBuilder.success(map);
    }

    @Value("${user_token_expires_days}")
    private  int expiresDays;
    private String getToken(User  user,HttpServletRequest request) {
        AuthorizationVo authorizationVo= httpHelper.getAuthorizationVo(request);
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE,  expiresDays);
        long time = calendar.getTime().getTime();
        String str=user.getId()+"$"+ authorizationVo.getAppid()+"$"+tokenVersion+"$"+time;
        String  token=EncryptionUtils.toDESToBASE64(str);
        return  token;
    }



}
